package com.duan.filter;

import com.alibaba.fastjson.JSONObject;
import com.duan.pojo.Result;
import com.duan.utils.JWTUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author db
 * @version 1.0
 * @description LoginFilter
 * @since 2024/1/11
 */
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        // 1. 获得请求路径
        String url = httpServletRequest.getRequestURL().toString();

        // 2. 判断请求的资源路径
        if(url.contains("/login")){
            // 登录功能，放行
            chain.doFilter(request,response);
            return;
        }

        // 3. 获取请求头token
        String token = httpServletRequest.getHeader("token");
        if(token == null){
            // 返回登录页面
            Result noLogin = Result.error("NO_LOGIN");
            // 使用原始方式给客户端响应数据
            // 把noLogin 对象转成json字符串返回
            String jsonString = JSONObject.toJSONString(noLogin);
            httpServletResponse.getWriter().write(jsonString);
            return;
        }
        // 4. 解析token
        try{
            JWTUtils.parseJWT(token);
        }catch (Exception e){
            // token存在问题
            // 返回登录页面
            Result noLogin = Result.error("NO_LOGIN");
            // 使用原始方式给客户端响应数据
            // 把noLogin 对象转成json字符串返回
            String jsonString = JSONObject.toJSONString(noLogin);
            httpServletResponse.getWriter().write(jsonString);
            return;
        }
        // 5. token解析成功，放行
        chain.doFilter(request,response);
    }
}
